//
//  BPRequestError.m
//  BPRequestTool_Example
//
//  Created by SiYugui on 2020/4/29.
//  Copyright © 2020年 xuhongji. All rights reserved.
//

#import "BPRequestError.h"

@implementation BPRequestError

+ (NSString*)errorStringWithError:(NSError*)error{
    
    NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
    if (response) {
        return [self serverDescriptionWithError:error];
    }else{
        return [self errorDescriptionWithErrorCode:error.code];
    }
}

#pragma mark -ErrorCode

+ (NSString*)errorDescriptionWithErrorCode:(NSInteger)errorCode{
    
    NSString *error = nil;
    
    switch (errorCode) {
            case NSURLErrorNotConnectedToInternet:
            error = @"请检查网络后重试";
            break;
            case NSURLErrorBadServerResponse:
            error = @"无法连接到服务器";
            break;
            case NSURLErrorTimedOut:
            error = @"连接服务器超时";
            break;
        default:
            error = @"连接服务器失败";
            break;
    }
    
    return error;
}

+ (NSInteger)errorCodeWithError:(NSError*)error{
    NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
    NSInteger statusCode = response.statusCode;
    return statusCode;
}

+ (NSString *)errorRequestURLWithError:(NSError*)error{
    NSHTTPURLResponse *response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey];
    return [response.URL absoluteString];
}

+ (NSString*)serverDescriptionWithError:(NSError*)error{
    
    NSInteger statusCode = [self errorCodeWithError:error];
    
    switch (statusCode) {
            case 404:
        {
            return @"未找到服务器";
        }
            break;
            case 412:
        {
            return @"用户会话已失效";
        }
            break;
            case 500:
        {
            return @"系统发生内部错误";
        }
            break;
        default:
            break;
    }
    
    NSData *data = error.userInfo
    [AFNetworkingOperationFailingURLResponseDataErrorKey];
    if (data) {
        NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if (info && [[info allKeys] containsObject:@"resultMsg"]) {
            return info[@"resultMsg"];
        }else{
            return @"服务器发生异常";
        }
    }else{
        return @"服务器发生异常";
    }
}

@end
